﻿using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
using System.Drawing.Design;
using System.IO;
using System.Runtime.InteropServices;

namespace LabMS.Web
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ValidateCode : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            CreateCheckCodeImage(RndNum(), context);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string RndNum()
        {
            int number;
            char code;
            string checkCode = String.Empty;

            System.Random random = new Random();

            for (int i = 0; i < 4; i++)
            {
                number = random.Next();
                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));
                checkCode += code.ToString();
            }

            return checkCode;
        }

        private void CreateCheckCodeImage(string checkCode, HttpContext context)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;

            context.Response.Cookies.Add(new HttpCookie("yzmcode", checkCode));

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 15);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器 
                Random random = new Random();
                //清空图片背景色 
                g.Clear(Color.Transparent);

                /*
                //画图片的背景噪音线 
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                */
                
                System.Drawing.Drawing2D.LinearGradientBrush bgBrush = new System.Drawing.Drawing2D.LinearGradientBrush(
                    new Rectangle(0, 0, image.Width, image.Height),
                    Color.FromArgb(20, 71, 116),
                    Color.FromArgb(20, 65, 109),
                    System.Drawing.Drawing2D.LinearGradientMode.Vertical);

                g.FillRectangle(bgBrush, new Rectangle(0, 0, image.Width, image.Height));

                Font font = new System.Drawing.Font("Arial", 10, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Bold));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(
                    new Rectangle(0, 0, image.Width, image.Height),
                    Color.White,
                    Color.DimGray,
                    1.2f,
                    true);
                g.DrawString(checkCode, font, brush, 0, 0);

                /*
                //画图片的前景噪音点 
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                */

                /*
                //画图片的边框线 
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                */

                // image = ToImageGif(image);

                // image.Save(Environment.CurrentDirectory + "\\Web\\code.png", System.Drawing.Imaging.ImageFormat.Png);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                context.Response.ClearContent();
                context.Response.ContentType = "image/Png";
                context.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        private static Bitmap ToImageGif(Bitmap originalBitMap)
        {
            int _Width = originalBitMap.Width;
            int _Height = originalBitMap.Height;

            System.IO.MemoryStream _MemoryStream = new MemoryStream();
            originalBitMap.Save(_MemoryStream, System.Drawing.Imaging.ImageFormat.Gif);
            Bitmap _MyBitMap256 = (Bitmap)Image.FromStream(_MemoryStream);  //保存成GIF 256色
            _MemoryStream.Dispose();
            //获取颜色索引
            System.Drawing.Imaging.ColorPalette _ColorPalette = _MyBitMap256.Palette;

            Hashtable _ColorHash = new Hashtable();
            for (int i = 0; i != _ColorPalette.Entries.Length; i++)
            {

                string _Key = _ColorPalette.Entries[i].R.ToString("X02") + _ColorPalette.Entries[i].G.ToString("X02") + _ColorPalette.Entries[i].B.ToString("X02");

                if (_ColorHash[_Key] == null) _ColorHash.Add(_Key, i);
            }


            ////建立新的图形
            Bitmap _Newbitmap = new Bitmap(_Width, _Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            _Newbitmap.Palette = _ColorPalette;  //设置索引

            Rectangle _Rect = new Rectangle(0, 0, _Width, _Height);
            //获取IMAGE数据
            System.Drawing.Imaging.BitmapData _BitmapData = _Newbitmap.LockBits(_Rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            byte[] _Bits = new byte[_Width * _Height];
            Int32 _BitsInt = 0;
            if (_BitmapData.Stride > 0)
            {
                _BitsInt = _BitmapData.Scan0.ToInt32();
            }
            else
            {
                _BitsInt = _BitmapData.Scan0.ToInt32() + _BitmapData.Stride * (_Height - 1);
            }

            int _Stride = Math.Abs(_BitmapData.Stride);

            for (int i = 0; i != _Height; i++)
            {
                for (int y = 0; y != _Width; y++)
                {
                    int _8BppPixel = i * _Stride + y;

                    Color _TempColor = _MyBitMap256.GetPixel(y, i);
                    int _Alpha = originalBitMap.GetPixel(y, i).A;

                    if (_Alpha == 0)
                    {
                        _Bits[_8BppPixel] = (byte)16;
                    }
                    else
                    {
                        string _Key = _TempColor.R.ToString("X02") + _TempColor.G.ToString("X02") + _TempColor.B.ToString("X02");

                        object _ValueIndex = _ColorHash[_Key];
                        if (_ValueIndex == null) return null;
                        _Bits[_8BppPixel] = (byte)((int)_ValueIndex);
                    }

                }
            }


            CopyArrayTo(_BitsInt, _Bits, _Height * _Stride);

            _Newbitmap.UnlockBits(_BitmapData);

            return _Newbitmap;
        }

        [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlMoveMemory", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern void CopyArrayTo([In(), System.Runtime.InteropServices.MarshalAs(UnmanagedType.I4)] Int32 hpvDest, [In(), Out()]byte[] hpvSource, int cbCopy);
    }
}
